/**
 * 多来源转单
 * Created by liyaoh on 2018/5/22.
 */
import React, { Component } from "react";

import {base, viewModel} from 'nc-lightapp-front';
let { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;

const {NCTable, NCButton, NCTabs, NCCol} = base;
const Button = NCButton;
const NCTabPane = NCTabs.NCTabPane;
const Table = NCTable;
const Col = NCCol;

//创建转单 params:单来源转单参数
export function createMultiTransferTable({
    showAll = false,
    allHeadId,
    allBodyId,
    allFullTableId,
    headPkIds,
    bodyPkIds,
    containerSelector,
    transferBtnText,
    onTransferBtnClick,
    onSelectedBtnClick,
    onChangeViewClick,
    onTabClick,
    selectArea,
    onClearAll,
    onSelectedItemRemove //已选列表清除回调
},params) {
    if(showAll){
        if (!this.state.transferTable.hasOwnProperty('allSelected')){
            this.state.transferTable['allSelected'] = {
                activeTab: 0,//当前高亮tab
                selectedShow: false,//显示已选列表
                masterAmount: 0, //主表已选数量
                bodyAmount: 0, //子表已选数量
                masterCheckedId: [], //存放已选主表id，用于复选框半选
                selIds: {}, //存放其他页签的主子表id
                showFullTable: false, //已选列表中是否显示主子拉平
                selectedData: {
                    selAll: false,
                    masterSelData: {},
                    childSelData: {}
                }
            }
        }
        
    }else{
        if (this.state.transferTable.allSelected){
            delete this.state.transferTable.allSelected
        }
    }
    const _this = this;
    let fullColumns = allFullTableId && this.state.meta[allFullTableId] ? this.state.meta[allFullTableId].items : [];//主子拉平模板
    //外层容器宽度
    let containerWidth = document.querySelector(containerSelector) && document.querySelector(containerSelector).clientWidth;
    let { transferTable } = this.state;
    this.onTabClick = onTabClick;
    this.onClearAll = onClearAll;
    this.onSelectedItemRemove = onSelectedItemRemove; //已选列表清除回调

    // 处理模板
    const createNewCol = (column) => {
        let result = [];
        if (!this.state.meta[allHeadId]){
            return false;
        }
        column = column || this.state.meta[allHeadId].items;
        column.map((item) => {
            let render = null;
            if (item.itemtype !== 'customer' && item.visible) {
                render = (text, record, index) => {
                    if (record[item.attrcode]){
                        let display = record[item.attrcode].display;
                        let value = record[item.attrcode].value;
                        let dom = '';
                        if (display || display === 0) {
                            dom = display
                        } else {
                            dom = value
                        }
                        return (
                            <span>{dom}</span>
                        )
                    }
                };
            } else {
                render = item.render
            }
            if (item.visible) {
                result.push({ ...item, render, key: item.attrcode, title: item.label })
            }
        });
        return result;
    };

    //子表添加复选框列
    const renderColumnsMultiSelectChild = (columns, records, indexs) => {
        let indexCol = {
            label: '序号',
            itemtype: 'customer',
            attrcode: "indexCol",
            dataIndex: "indexCol",
            visible: true,
            width: 80,
            render: (text, record2, index) => {
                return (
                    <span>
                        {index + 1}
                    </span>
                )
            }
        }; // 添加序号列
        // let newColumn = columns;
        // newColumn = indexCol.concat(newColumn);

        let oprColumn = {
            label: '操作',
            attrcode: "operate",
            itemtype: 'customer',
            dataIndex: "operate",
            width: 50,
            visible: true,
            render: (text, record, index) => {
                return (
                    <a href="javascript:;" onClick={ clearSelectedData.bind(this,'body',records.key,record.key,record)}>移除</a>
                );
            }
        }

        return [indexCol, ...columns, oprColumn];
    };

    //统计已选列表数量
    const getSelectedAmount = () => {
        let allSelected = this.state.transferTable.allSelected;//多来源转单全部页签
        //多来源有全部时统计全部页签的勾选重量
        if (allSelected) {
            let bodys = 0;
            Object.values(allSelected.selIds).forEach(item => {
                bodys += item.length;
            });
            let masterAmount = Object.keys(allSelected.selIds).length;
            let bodyAmount = bodys;
            allSelected.masterAmount = masterAmount;
            allSelected.bodyAmount = bodyAmount;
            return { masterAmount, bodyAmount };
        }
    }
    let selectedAmount = getSelectedAmount();//已选数据数量

    //清除对应主/子表数据
    const clearSelectedData = (type,headId,bodyId,record) => {
        let delBodyData;
        for (let key in transferTable) {
            let selectedData = key !== 'allSelected' ? transferTable[key].selected.selectedData : transferTable[key].selectedData;
            let masterSelData = selectedData.masterSelData;
            let childSelData = selectedData.childSelData;
            selectedData.selAll = false;
            if(type === 'head'){
                if( key === 'allSelected' ){
                    delBodyData = childSelData[headId]; //记录被删除的子表数据
                }
                delete masterSelData[headId];
                delete childSelData[headId];
                delete transferTable.allSelected.selIds[headId];//删除全部已选中对应主表id
                delete transferTable.allSelected.selectedData.masterSelData[headId];
            }else if(type === 'body'){
                for (let val in childSelData[headId]){
                    let selHeadId = transferTable.allSelected.selIds[headId];
                    if (selHeadId && val === bodyId && selHeadId.includes(val)){ //删除全部已选中对应子表id
                        selHeadId.splice(selHeadId.indexOf(val),1);
                    }
                    if (val === bodyId){ //删除相应页签子表id
                        delete childSelData[headId][val];
                    }
                    if (Object.keys(childSelData[headId]).length === 0) {
                        delete childSelData[headId];
                        delete masterSelData[headId];
                        delete transferTable.allSelected.selIds[headId];
                        delete transferTable.allSelected.selectedData.masterSelData[headId];
                        delete transferTable.allSelected.selectedData.childSelData[headId];
                    }
                }
            }
            if (key !== 'allSelected') setMasterId(key, headId, false);
        }
        this.setState({
            transferTable
        },() => {
            let bodySelData = delBodyData ? Object.values(delBodyData).map(item => item.data.values || item.data) : [];
            onSelectedItemRemove && onSelectedItemRemove(record, bodySelData);
        });
    }

    //清空全部数据
    const clearAllSelectedData = () => {
        transferTable.allSelected.selectedData.masterSelData = {};
        transferTable.allSelected.selectedData.childSelData = {};
        transferTable.allSelected.selIds = {};
        transferTable.allSelected.masterAmount = 0;
        transferTable.allSelected.bodyAmount = 0;
        for (let key in transferTable) {
            if (key !== 'allSelected') {
                transferTable[key].selected.masterCheckedId = [];//清空已选主表id
                transferTable[key].selected.selectedData.selAll = false;//取消全选
                transferTable[key].selected.selectedData.masterSelData = {};
                transferTable[key].selected.selectedData.childSelData = {};
            }
        }
        this.setState({
            transferTable
        }, () => {
            onClearAll && onClearAll();
        });
    }

    //选择主/子表时记录主表id key:转单id headId:主表id flag:选中/取消选中
    const setMasterId = (key,headId, flag) => {
        let { masterCheckedId, selectedData } = transferTable[key].selected;
        if (!masterCheckedId.includes(headId) && flag) {
            masterCheckedId.push(headId);
        } else if (masterCheckedId.indexOf(headId) !== -1 && !selectedData.selAll) {
            masterCheckedId.splice(masterCheckedId.indexOf(headId), 1);
        }
    }

    //设置已选列表columns
    const setSelectedColumns = (columns) => {
        let result = [];
        // 添加序号列
        let indexCol = {
            label: '序号',
            attrcode: "indexCol",
            itemtype: 'customer',
            dataIndex: "indexCol",
            visible: true,
            width: 80,
            render: (text, record2, index) => {
                return (
                    <span>
                        {index + 1}
                    </span>
                )
            }
        }; 
        let operateColumn = {
            title: '操作',
            attrcode: "operate",
            itemtype: 'customer',
            dataIndex: "operate",
            width: 50,
            visible: true,
            render: (text, record, index) => {
                return (
                    <a href="javascript:;" onClick={!transferTable.allSelected.showFullTable ? clearSelectedData.bind(this, 'head', record.key, '',record) : clearSelectedData.bind(this, 'body', record.headKey, record.key,record)}>移除</a>
                );
            }
        }
        // columns && columns.map(item => {
        //     if (item.attrcode !== 'checkbox' && item.label !== '操作') {
        //         result.push(item);
        //     }
        // });
        return [indexCol, ...columns, operateColumn];
    }

    //  处理数据
    const createNewData = (data) => {
        let datas = [];
        data.map((val, index) => {
            val = val.values || val;
            datas.push(val);
        });
        return datas
    };
    
    //渲染子表表格数据
    const expandedRowRender = (record, index) => {
        let bodyColumn = this.state.meta[allBodyId].items;//子表模板
        let newColumn = bodyColumn;
        let classByType = null;
        let indexCol = [
            {
                label: '序号',
                attrcode: "indexCol",
                itemtype: 'customer',
                dataIndex: "indexCol",
                visible: true,
                width: 80,
                render: (text, record2, index) => {
                    return (
                        <span>
                            {index + 1}
                        </span>
                    )
                }
            }
        ]; // 添加序号列
        // newColumn = indexCol.concat(newColumn);
        newColumn = renderColumnsMultiSelectChild.call(this, newColumn, record, index);

        let data = null;
        //已选列表的子表移除时需要删除行数据
        data = createNewData(Object.values(transferTable.allSelected.selectedData.childSelData[record.key] || {}).map(item => item.data));

        return (
            <Col md={12} xs={12} sm={12}>
                <Table
                    columns={createNewCol(newColumn)}
                    data={data}
                    scroll={{ x: true, y: 450 }}
                />

            </Col>
        );
    };

    //获取已选列表主表数据
    const getMasterData = (data) => {
        return Object.values(data.masterSelData).map(item => item.data);
    }

    //点击页签
    const handleTabClick = (key) => {
        if (this.state.transferTable.allSelected){
            this.state.transferTable.allSelected.activeTab = key;
        }
        this.setState({
            transferTable: this.state.transferTable
        },() => {
            if (typeof onTabClick === 'function') {
                onTabClick(key)
            }
        });
    }
    
    //关闭已选列表
    const closeSelectedList = () => {
        this.state.transferTable.allSelected.selectedShow = false;
        this.setState({
            transferTable: this.state.transferTable
        });
    }

    //查看已选列表
    const viewSelectedList = () => {
        let selectedData = this.state.transferTable.allSelected.selectedData;
        //先清空已选列表
        selectedData.masterSelData = {};
        selectedData.childSelData = {};
        this.setState({
            transferTable: this.state.transferTable
        },() => {
            if (typeof onSelectedBtnClick === 'function'){
                onSelectedBtnClick();
            } 
        });
        if(!showAll){
            getAllSelectedData();
        }
        if (!this.state.meta[allHeadId]){
            console.error('没有加载全部页签模板');
            return false;
        }
        if (transferTable.allSelected.masterAmount == 0 && transferTable.allSelected.bodyAmount == 0) {
            return false;
        } else {
            transferTable.allSelected.selectedShow = !transferTable.allSelected.selectedShow;//已选列表弹窗显示状态
            this.setState({
                transferTable: this.state.transferTable
            });
        }
    }

    //点击切换视图
    const handleChangeView = () => {
        if (typeof onChangeViewClick === 'function') {
            onChangeViewClick();
        }
    }

    //获取已选列表主子拉平数据
    const getSelectedFullData = (data) => {
        let { masterSelData, childSelData } = data;
        let result = [];
        for (let key in childSelData) {
            Object.values(childSelData[key]).forEach(item => {
                let childVal = item.data.values || item.data;
                let newData = Object.assign(JSON.parse(JSON.stringify(masterSelData[key].data)), JSON.parse(JSON.stringify(childVal)));//合并后的主子拉平数据
                newData.headKey = key;
                result.push(newData);
            });
        }
        return result;
    }

    //获取多来源转单已选数据
    const getAllSelectedData = () => {
        let { allSelected } = this.state.transferTable;
        let headSelData = {},
            bodySelData = {};
        for (let key in transferTable){
            if (key !== 'allSelected'){
                let masterSelData = transferTable[key].selected.selectedData.masterSelData;
                let childSelData = transferTable[key].selected.selectedData.childSelData;
                Object.assign(headSelData, masterSelData);
                Object.assign(bodySelData, childSelData);
            }
        }
        allSelected.selectedData.masterSelData = headSelData;
        allSelected.selectedData.childSelData = bodySelData;
    }

    //点击生成按钮
    const handleGenerateClick = () => {
        let selIds = [];
        getAllSelectedData();
        //获取已选列表主子表id
        if (!headPkIds || !bodyPkIds){
            console.error("没有传主表或子表主键字段")
        }
        let masterData = transferTable.allSelected.selectedData.masterSelData;
        for (let key in masterData) {
            let childData = transferTable.allSelected.selectedData.childSelData[key];
            let bodys = [];
            for (let id in childData) {
                let values = childData[id].data.values || childData[id].data;
                bodyPkIds && bodyPkIds.map(pk => {
                    let cData = childData[id].data.values || childData[id].data;
                    if (cData.hasOwnProperty(pk)) {
                        bodys.push({
                            [pk]: id,
                            ts: values.ts.value
                        })
                    }
                });
            }
            headPkIds && headPkIds.map(pk => {
                if (masterData[key].data.hasOwnProperty(pk)) {
                    selIds.push({
                        head: {
                            [pk]: key,
                            ts: masterData[key].data.ts.value
                        },
                        bodys: bodys
                    });
                }
            });
        }
        
        setGlobalStorage('sessionStorage', 'multiTransferIds', JSON.stringify(selIds));//将主子表id缓存起来
        this.setState({
            transferTable: this.state.transferTable
        },
            () => {
                if (typeof onTransferBtnClick === 'function') {
                    onTransferBtnClick(selIds);
                }
            }
        );
    }

    if(Array.isArray(params)){
        return <div className="multitransfer-container transfertable-main">
            {
                !showAll || !transferTable.allSelected.selectedShow ? 
                    <NCTabs
                        onChange={key => handleTabClick(key)}
                        animated={false}
                    >
                        {params && params.map((item,index) => {
                            let { tabName, searchArea, onTabClick, ...transferParams } = item;
                            transferParams.showSeletedArea = !showAll;//全部多来源不显示单个已选列表
                            transferParams.showSeletedBtn = showAll;//普通多来源不显示查看已选按钮

                            return <NCTabPane tab={item.tabName} key={index}>
                                    <div className="multi-transfer-container">
                                        {/* 查询区域 */}
                                        <div className="transfer-search-container">
                                            {searchArea && searchArea()}
                                        </div>
                                        {/* 转单区域 */}
                                        {_this.transferTable.createTransferTable(transferParams)}
                                    </div>
                                    
                                </NCTabPane>
                        })}
                    </NCTabs>
                : ''
            }
                {
                    showAll && transferTable.allSelected.selectedShow ?
                        <div className="selected-list">
                            <div className="header-area">
                                <span className="header-title">已选列表</span>
                                <div className="header-right">
                                    <span className="item" onClick={clearAllSelectedData.bind(this)}>清空</span>
                                    <a href="javascript:;" onClick={handleChangeView.bind(this)}>切换</a>
                                    <span className="hide iconfont icon-mianbaoxie" onClick={closeSelectedList.bind(this)}></span>
                                </div>
                            </div>
                            <div className="content-area">
                            {
                                !transferTable.allSelected.showFullTable ?
                                    <NCTable
                                        className="insertTable"
                                        columns={setSelectedColumns(createNewCol())}
                                        data={getMasterData(transferTable.allSelected.selectedData)}
                                        expandedRowRender={(record, index) => expandedRowRender(record, index)}
                                        rowKey={(record) => record.key}
                                        scroll={{ x: true }}
                                    />
                                    :
                                    //主子拉平
                                    <NCTable
                                        columns={setSelectedColumns(createNewCol(fullColumns))}
                                        data={getSelectedFullData(transferTable.allSelected.selectedData)}
                                        scroll={{ x: true }}
                                    />

                            }
                            </div>
                        </div>
                    : ''
                }
                {
                    showAll ? 
                    <div className="fixed-bottom-outer" style={{ width: containerWidth }}>
                        <div className="fixed-bottom-container bottom-area-container">
                            <div className="area-left">
                                {
                                    this.state.transferTable.allSelected.selectedShow ?
                                        <Button className="middle-btn" onClick={closeSelectedList.bind(this)}>全部列表</Button>
                                        :
                                        <Button
                                            className="middle-btn"
                                            onClick={viewSelectedList.bind(this)}
                                            disabled={selectedAmount.bodyAmount == 0}
                                        >
                                            查看已选
                                        </Button>
                                }
                            </div>
                            <div className="area-center">
                                <span>合计：{selectedAmount.masterAmount}条<span style={{ marginLeft: 26 }}>共{selectedAmount.bodyAmount}行</span></span>
                            </div>
                            {
                                selectArea ? 
                                <div className="area-custom">
                                    {selectArea && typeof selectArea == 'function' && selectArea()}
                                </div> : ''
                            }
                            {
                                params.map((item,index) => {
                                    let hideHtml = {};
                                    if (index != transferTable.allSelected.activeTab){
                                        hideHtml = {display: 'none'};
                                    }
                                    return item.selectArea && <div className="area-custom" style={hideHtml}>
                                        {typeof item.selectArea == 'function' && item.selectArea()}
                                    </div>
                                })
                            }
                            <div className="area-right">
                                <Button
                                    className="main-button large-btn"
                                    onClick={handleGenerateClick.bind(this)}
                                    disabled={selectedAmount.bodyAmount == 0}
                                >{transferBtnText}</Button>
                            </div>
                        </div>
                    </div>
                    : ''
                }
        </div>
        
    }
}
